package com.smag.web.controller.farming;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smag.common.annotation.Anonymous;
import com.smag.common.constant.SystemConstants;
import com.smag.common.core.controller.BaseController;
import com.smag.common.core.domain.AjaxResult;
import com.smag.common.core.domain.entity.FarmArticle;
import com.smag.common.core.domain.entity.FarmProduct;
import com.smag.common.core.redis.RedisCache;
import com.smag.system.service.FarmArticleService;
import com.smag.system.service.FarmProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/farming/article")
@Anonymous
public class ArticleController extends BaseController {

    @Autowired
    private FarmArticleService farmarticleService;

    @Autowired
    private FarmProductService farmProductService;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/hotArticleList")
    public AjaxResult hotArticle() {
        return farmarticleService.hotArticleList();
    }

    @GetMapping("/articleList")
    public AjaxResult getArticleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //每调一次查询方法先将浏览量存入redis
        LambdaQueryWrapper<FarmArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FarmArticle::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<FarmArticle> farmArticleList = farmarticleService.list(queryWrapper);
        Map<String, Integer> viewCountMap = farmArticleList.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(), article -> article.getViewCount().intValue()));
        redisCache.setCacheMap(SystemConstants.VIEW_COUNT,viewCountMap);

        return farmarticleService.getArticleList(pageNum,pageSize,categoryId);
    }

    @GetMapping("/{id}")
    public AjaxResult getArticleDetail(@PathVariable("id") Long id) {
        return farmarticleService.getArticleDetail(id);
    }

    @PutMapping("/updateViewCount/{id}")
    public AjaxResult updateViewCount(@PathVariable("id") Long id) {
        return farmarticleService.updateViewCount(id);
    }

    @GetMapping("/getProduct/{id}")
    public AjaxResult selectFarmProductList(@PathVariable("id") Long id) {
        FarmProduct farmProduct = farmProductService.selectFarmProductByArticleId(id);
        if(farmProduct == null) {
            return success("null");
        }
        return success(farmProduct);
    }
}
